<script setup>
import settings from "@/settings";
import {useRouter} from "vue-router";
import {HOME_URL} from "@/config/index.js";
import {initDynamicRouter} from "@/router/modules/dynamicRouter.js";
import {useAccountStore, useTabsStore, useKeepAliveStore, useUserStore,} from "@/store/index.js";
import {apiParam, getAssets} from "@/utils/index.js";
import {skyMsgSuccess, skyMsgError} from "@/utils/sky.js";
import {getAccount, login} from "@/apis/login/index.js";
import {User, Lock, Open, Search} from "@element-plus/icons-vue";

const router = useRouter();
const logo = getAssets("images/logo/logo.svg");
const refLoginForm = ref();
const accountStore = useAccountStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const userStore = useUserStore();
const pageData = ref({
  isShowAccount: false,
  loading: false,
  searchAccount: "",
  accountList: accountStore.account,
  loginForm: {
    username: "",
    password: "",
    account: "",
  },
  loginRules: {
    username: [{required: true, message: "用户名不能为空", trigger: "blur"}],
    password: [{required: true, message: "密码不能为空", trigger: "blur"}],
    account: [{required: true, message: "用户账套不能为空", trigger: "blur"}]
  },
});
const method = reactive({
  openAccount: () => {
    pageData.value.isShowAccount = true;
  },
  search: () => {
    const data = apiParam("2.0", "SYS.BookDAL.GetBooks",
      {CustId: pageData.value.searchAccount});
    getAccount(data).then((res) => {
      if (res.status >= 0) {
        if (res.data.length === 0) {
          pageData.value.searchAccount = "";
          return skyMsgError("没有找到该账套信息");
        }
        // 判断是否已经添加
        res.data.forEach(item => {
          const flag = pageData.value.accountList.some(account => account.BookName === item.BookName);
          if (!flag) {
            skyMsgSuccess("获取成功");
            pageData.value.searchAccount = "";
            pageData.value.isShowAccount = false;
            accountStore.setAccount(item);
          }
        });
      }
    });
  },
  skyLogin: () => {
    if (!refLoginForm.value) return;
    refLoginForm.value.validate(async (valid, fields) => {
      if (valid) {
        pageData.value.loading = true;
        try {
          const data = apiParam("2.0", "SYS.UserDAL.Login",
            [pageData.value.loginForm.username, {
              Password: pageData.value.loginForm.password,
              CustId: pageData.value.loginForm.account,
              BookName: pageData.value.accountList.find(item => item.CustId === pageData.value.loginForm.account).BookName,
              ClientType: 0,
              ClientVersion: "1.0.0.0",
              HostName: null,
              IPAddress: null,
              MacAddress: null,
              EncyptType: 0,
              DeviceId: "",
              ForceLogin: false,
            }]);
          const res = await login(data);
          userStore.setId(pageData.value.loginForm.username);
          userStore.setToken(res.data);
          // 添加动态路由 AND 用户按钮 AND 角色信息 AND 用户个人信息
          await initDynamicRouter();
          // 清空 tabs数据、keepAlive缓存数据
          await tabsStore.setTab([]);
          await keepAliveStore.setKeepAliveName([]);
          skyMsgSuccess("登录成功");
          // 跳转到首页
          pageData.value.loading = false;
          await router.push(HOME_URL);
        } catch (error) {
          // 等待1秒关闭loading
          let loadingTime = 1;
          setInterval(() => {
            loadingTime--;
            if (loadingTime === 0) {
              pageData.value.loading = false;
            }
          }, 1000);
        }
      } else {
        skyMsgError("校验失败，信息填写有误");
      }
    });
  },
});
</script>

<template>
  <div class="form center">
    <div class="flex items-center">
      <el-image class="rounded-full w-36px h-36px" :src="logo"/>
      <div class="ml-6px font-bold text-xl">{{ settings.loginTitle || "KOI-ADMIN 管理平台" }}</div>
    </div>
    <div class="flex items-center space-x-3 text-gray-400 mt-16px mb-16px">
      <span class="h-1px w-16 bg-gray-300 inline-block"></span>
      <span class="text-center">账号密码登录</span>
      <span class="h-1px w-16 bg-gray-300 inline-block"></span>
    </div>
    <!-- 输入框盒子 -->
    <el-form ref="refLoginForm" :model="pageData.loginForm" :rules="pageData.loginRules" class="w-260px">
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item prop="username">
            <el-input type="text" v-model="pageData.loginForm.username" placeholder="请输入用户名" :suffix-icon="User"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="password">
            <el-input type="password" v-model="pageData.loginForm.password" placeholder="请输入密码" show-password
                      :suffix-icon="Lock"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="account">
            <el-select v-model="pageData.loginForm.account" placeholder="选择账套" clearable>
              <el-option
                v-for="item in pageData.accountList"
                :key="item.CustId"
                :label="item.BookName"
                :value="item.CustId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <span style="margin-left: 200px; color: #3a8ee6"
                  @click="method.openAccount">客户编号</span>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 登录按钮 -->
      <el-form-item>
        <el-button class="w-245px bg-[--el-color-primary]"
                   type="primary" v-if="!pageData.loading"
                   round @click="method.skyLogin">
          登录
        </el-button>
        <el-button class="w-245px bg-[--el-color-primary]" type="primary" v-if="pageData.loading" round
                   :loading="pageData.loading">
          登录中
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <el-dialog class="search-dialog" v-model="pageData.isShowAccount" :width="500" :show-close="false" top="10vh">
    <span style="font-size: 25px">客户编号</span>
    <el-input
      style="margin-top: 10px"
      v-model="pageData.searchAccount"
      placeholder="请输入客户编号, 回车确认"
      size="large"
      clearable
      :prefix-icon="Search"
      @keydown.enter="method.search"
    ></el-input>
    <template #footer>
      <el-button type="primary" @click="method.search">确定</el-button>
      <el-button type="danger" @click="pageData.isShowAccount=false; pageData.searchAccount=''">取消</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.form {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
